package com.knowswift.security.handler.success;


import com.knowswift.common.utils.JwtTokenUtils;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import com.knowswift.security.account.UserVO;
import com.knowswift.security.handler.AbstractLoginSuccessHandler;
import com.knowswift.security.log.LoginLogService;
import com.knowswift.security.token.UserUsernamePasswordAuthenticationToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserPasswordLoginSuccessHandler extends AbstractLoginSuccessHandler {

    @Resource
    private UserService userService;

    @Resource
    private LoginLogService loginLogService;


    @Override
    public Object preAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        UserUsernamePasswordAuthenticationToken authenticationToken = (UserUsernamePasswordAuthenticationToken) authentication;
        String appleId = authenticationToken.getAppleId();
        User user = (User) authentication.getPrincipal();
//        if (!user.getRole().equals(PropertyConfig.ROLE_USER)) {
//            sendResponse(httpServletResponse, Result.NO_ACCESS, "无权访问", null);
//            return null;
//        }
        if (StringUtils.isNotBlank(appleId)) {
            user.setAppleId(appleId);
        }
        user.setAppTokenVersion(user.getAppTokenVersion() + 1);
        userService.updateById(user);
        Map<String, Object> claims = new HashMap<>();
        claims.put("tokenVersion", user.getAppTokenVersion());
        String token = JwtTokenUtils.generateToken(claims, user.getId());
        UserVO userVO = WrappedBeanCopier.copyProperties(user, UserVO.class);
        userVO.setToken(token);
        return userVO;
    }
}
